package com.homework.HomeAcount.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.homework.HomeAcount.dao.ResourceDao;
import com.homework.HomeAcount.entity.Resource;
import com.homework.HomeAcount.entity.TreeNode;
import com.homework.HomeAcount.service.ResourceService;

/**
 * 资源操作相关Service
 * Project Name:HomeAcount 
 * @author gk
 * TODO
 * Date:2015年12月23日上午10:55:32 
 * Copyright (c) 2015, gkaigk@126.com All Rights Reserved. 
 * @Version 1.0
 */
@Service("resourceService")
public class ResourceServiceImpl implements ResourceService {
	
	@Autowired
	private ResourceDao resourceDao;

	@Override
	public List<TreeNode> getResourceTreeNodes() {
		List<Resource> topList = resourceDao.getTopResource();
		List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		if(null != topList && topList.size() > 0) {
			for(int i = 0; i < topList.size(); i++) {
				TreeNode treeNode = new TreeNode();
				Resource resource = topList.get(i);
				treeNode.setId(resource.getId());
				treeNode.setName(resource.getName());
				treeNode.setIsParent(true);
				treeNode.setOpen(true);
				treeNodes.add(treeNode);
				List<TreeNode> subList = getSubResourceTreeNodes(resource.getId());
				treeNode.setChildren(subList);
			}
		}
		return treeNodes;
	}

	@Override
	public List<TreeNode> getSubResourceTreeNodes(String id) {
		List<Resource> subTreeNodes = resourceDao.getSubResource(id);
		List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		if(null != subTreeNodes && subTreeNodes.size() > 0) {
			for(int i = 0; i < subTreeNodes.size(); i++) {
				TreeNode treeNode = new TreeNode();
				Resource resource = subTreeNodes.get(i);
				treeNode.setId(resource.getId());
				treeNode.setName(resource.getName());
				treeNode.setpId(id);
				treeNode.setOpen(true);
				treeNodes.add(treeNode);
				List<TreeNode> subList = getSubResourceTreeNodes(resource.getId());
				treeNode.setChildren(subList);
			}
		}
		return treeNodes;
	}

	@Override
	public Resource getResourceById(String id) {
		return resourceDao.getResourceById(id);
	}

	@Override
	public List<Resource> getParentResources() {
		return resourceDao.getParentResources();
	}

	@Override
	public void updateResourceById(Resource resource) throws Exception {
		resourceDao.updateResourceById(resource);
	}

	@Override
	public void insertResource(Resource resource) throws Exception {
		resourceDao.insertResource(resource);
	}

}
